import numpy as np
import cv2
from PIL import Image, ImageOps
from tflite_runtime.interpreter import Interpreter

# 加载 TensorFlow Lite 模型
interpreter = Interpreter(model_path="../model/keras_model.tflite")
interpreter.allocate_tensors()

# 获取输入和输出张量的详细信息
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# 打开摄像头
cap = cv2.VideoCapture(0)  # 0 是默认摄像头，改为其他数字可使用其他摄像头

if not cap.isOpened():
    print("无法打开摄像头")
    exit()

# 循环读取每一帧
while True:
    # 读取摄像头中的一帧
    ret, frame = cap.read()
    if not ret:
        print("无法读取摄像头画面")
        break

    # # 转换为 PIL 图像进行处理
    # image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)).convert("RGB")
    #
    # # 预处理输入图像
    # size = (224, 224)
    # image = ImageOps.fit(image, size, Image.LANCZOS)
    #
    # # 转换为 numpy 数组并归一化
    # image_array = np.asarray(image)
    # normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
    #
    # # 将图像数据传入模型
    # input_data = np.expand_dims(normalized_image_array, axis=0).astype(np.float32)
    # interpreter.set_tensor(input_details[0]['index'], input_data)
    #
    # # 执行推理
    # interpreter.invoke()
    #
    # # 获取输出结果
    # output_data = interpreter.get_tensor(output_details[0]['index'])
    #
    # # 获取预测结果
    # index = np.argmax(output_data)
    # class_names = open("../model/labels.txt", "r").readlines()
    # class_name = class_names[index]
    # confidence_score = output_data[0][index]
    #
    # # 在屏幕上显示预测结果
    # cv2.putText(frame, f"Class: {class_name.strip()}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2,
    #             cv2.LINE_AA)
    # cv2.putText(frame, f"Confidence: {confidence_score:.2f}", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2,
    #             cv2.LINE_AA)

    # 显示摄像头画面
    cv2.imshow("Camera Feed", frame)

    # 按 'q' 键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头资源并关闭窗口
cap.release()
cv2.destroyAllWindows()
